package com.itheima.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.itheima.domain.Cart;
import com.itheima.utils.JDBCUtils;

/**
 * 数据库表cart增删查改DAO层操作
 * @author dell-pc
 *
 */
public class CartDao {

	/**
	 * 查询某个用户所有的购物车信息
	 * @param username
	 * @return
	 * @throws SQLException 
	 */
	public List<Cart> findAllCart(String username) throws SQLException{
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select * from cart where username = ?";
		List<Cart> listCart = qr.query(sql, new BeanListHandler<Cart>(Cart.class),username);
		return listCart;
	}
	
	/**
	 * 添加操作
	 * @param cart
	 * @return
	 * @throws SQLException 
	 */
	public int addCart(Cart cart) throws SQLException{
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		//编写sql
		String sql = "insert into cart values(null,?,?,?,?,?)";
		//设置参数
		Object params[] = {cart.getBookName(),cart.getBookCount(),cart.getBookPrice(),cart.getUsername(),cart.getC_desc()};
		//执行sql语句，并返回影响行数
		int i = qr.update(sql, params);
		return i;
	}
	
	/**
	 * 删除操作
	 * @param bid
	 * @return
	 * @throws SQLException 
	 */
	public int deleteCart(Integer cid) throws SQLException{
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		//编写sql
		String sql = "delete from cart where cid=?";	
		//执行sql语句，并返回影响行数
		int i = qr.update(sql, cid);
		return i;
	}

	/**
	 * 获得分页总记录数
	 * @param username
	 * @return
	 * @throws SQLException 
	 */
	public int findCount(String username) throws SQLException {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select count(*) from cart where username = ?";
		Long count = (Long) qr.query(sql, new ScalarHandler(),username);
		return count.intValue();
	}

	/**
	 * 获得分页数据
	 * @param begin
	 * @param pageSize
	 * @param username
	 * @return
	 * @throws SQLException 
	 */
	public List<Cart> findByPage(int begin, int pageSize, String username) throws SQLException {
		QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select * from cart where username = ? limit ?,?";
		List<Cart> listCart = qr.query(sql, new BeanListHandler<Cart>(Cart.class),username,begin,pageSize);
		return listCart;
	}
}
